/*
  */
package competition;

import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;

/**
 *
 * @author atchounikine
 */

public class JpaUtil {

private static EntityManagerFactory emf;
    private static ThreadLocal<EntityManager> tl = new ThreadLocal<EntityManager>();


    public static EntityManager getEntityManager() {
        EntityManager em = tl.get();
        if (em == null) {
            emf = getEntityManagerFactory();
            em = emf.createEntityManager();
            tl.set(em);
        }
        return em;
    }

    private static EntityManagerFactory getEntityManagerFactory() {
	//TODO Changer le nom du persistence unit
        if (emf == null) {
            emf = Persistence.createEntityManagerFactory("CompetitionPU");
        }
        return emf;
    }

    public static void closeEntityManager() {
        EntityManager em = tl.get();
        if (em != null) {
            em.close();
            tl.set(null);
        }
    }

    public static EntityTransaction getTransactionEntityManager() throws Exception {
        return getEntityManager().getTransaction();
    }
}